{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Make sure you already run\n",
    "\n",
    "1. [wav2vec-preprocessing.ipynb](wav2vec-preprocessing.ipynb)\n",
    "2. [wav2vec.ipynb](wav2vec.ipynb)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '1'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:516: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:517: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:518: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:519: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:520: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorflow/python/framework/dtypes.py:525: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint8 = np.dtype([(\"qint8\", np.int8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint8 = np.dtype([(\"quint8\", np.uint8, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint16 = np.dtype([(\"qint16\", np.int16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:544: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_quint16 = np.dtype([(\"quint16\", np.uint16, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:545: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  _np_qint32 = np.dtype([(\"qint32\", np.int32, 1)])\n",
      "/home/husein/.local/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:550: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.\n",
      "  np_resource = np.dtype([(\"resource\", np.ubyte, 1)])\n"
     ]
    }
   ],
   "source": [
    "import librosa\n",
    "import tensorflow as tf\n",
    "import glob\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pickle\n",
    "\n",
    "with open('train-wav.pkl', 'rb') as fopen:\n",
    "    X = pickle.load(fopen)\n",
    "    \n",
    "with open('test-wav.pkl', 'rb') as fopen:\n",
    "    Y = pickle.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'augment/OAF_boat_happy-3.wav'"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X['x'][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "import re\n",
    "\n",
    "vocab = \"ES abcdefghijklmnopqrstuvwxyz'\"\n",
    "char2idx = {char: idx for idx, char in enumerate(vocab)}\n",
    "idx2char = {idx: char for idx, char in enumerate(vocab)}\n",
    "\n",
    "def text2idx(text):\n",
    "    text = re.sub(r'[^a-z ]', '', text.lower()).strip()\n",
    "    converted = [char2idx[char] for char in text]\n",
    "    return text, converted"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = []\n",
    "for fpath in X['x']:\n",
    "    fpath = fpath.split('/')[1]\n",
    "    splitted = fpath.split('-')\n",
    "    if len(splitted) == 2:\n",
    "        splitted[1] = splitted[1].split('.')[1]\n",
    "        fpath = splitted[0] + '.' + splitted[1]\n",
    "    with open('data/' + fpath.replace('wav', 'txt')) as fopen:\n",
    "        text, converted = text2idx(fopen.read())\n",
    "    train_Y.append(converted)\n",
    "    \n",
    "train_X = X['X']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(16341, 16341)"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(train_X), len(train_Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "test_Y = []\n",
    "for fpath in Y['y']:\n",
    "    fpath = fpath.split('/')[1]\n",
    "    splitted = fpath.split('-')\n",
    "    if len(splitted) == 2:\n",
    "        splitted[1] = splitted[1].split('.')[1]\n",
    "        fpath = splitted[0] + '.' + splitted[1]\n",
    "    with open('data/' + fpath.replace('wav', 'txt')) as fopen:\n",
    "        text, converted = text2idx(fopen.read())\n",
    "    test_Y.append(converted)\n",
    "    \n",
    "test_X = Y['Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(560, 560)"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(test_X), len(test_Y)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "# follow hyperparameters from here, https://github.com/pytorch/fairseq/tree/master/examples/wav2vec\n",
    "\n",
    "features = [(512, 10, 5), (512, 8, 4), (512, 4, 2), (512, 4, 2), (512, 4, 2), (512, 1, 1), (512, 1, 1)]\n",
    "aggs = [(512, 2, 1), (512, 3, 1), (512, 4, 1), (512, 5, 1), (512, 6, 1), (512, 7, 1), (512, 8, 1), (512, 9, 1), \n",
    "        (512, 10, 1), (512, 11, 1), (512, 12, 1), (512, 13, 1)]\n",
    "num_negatives = 10\n",
    "prediction_steps = 12\n",
    "learning_rate = 1e-5\n",
    "min_learning_rate = 1e-9\n",
    "max_learning_rate = 0.005\n",
    "learning_scheduler = 'cosine'\n",
    "max_update = 400000\n",
    "residual_scale = 0.5\n",
    "log_compression = True\n",
    "warmup_updates = 50\n",
    "warmup_init_lr = 1e-07\n",
    "batch_size = 32\n",
    "epoch = 10\n",
    "total_steps = batch_size * epoch"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [],
   "source": [
    "import math\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[0]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "def layer_norm(input_tensor, name=None):\n",
    "    return tf.contrib.layers.layer_norm(\n",
    "      inputs=input_tensor, begin_norm_axis=-1, begin_params_axis=-1, scope=name)\n",
    "\n",
    "\n",
    "def cnn_block(x, hidden_dim, kernel_size, strides):\n",
    "    x =  tf.layers.conv1d(inputs = x,\n",
    "                          filters = hidden_dim,\n",
    "                          kernel_size = kernel_size,\n",
    "                          strides = strides)\n",
    "    x = layer_norm(x)\n",
    "    x = tf.nn.relu(x)\n",
    "    return x\n",
    "\n",
    "def cnn_aggregator(x, hidden_dim, kernel_size, strides):\n",
    "    ka = kernel_size // 2\n",
    "    kb = ka - 1 if kernel_size % 2 == 0 else ka\n",
    "    pad = tf.zeros([tf.shape(x)[0], kb + ka, hidden_dim])\n",
    "    x =  tf.layers.conv1d(inputs = tf.concat([pad, x], 1),\n",
    "                          filters = hidden_dim,\n",
    "                          kernel_size = kernel_size,\n",
    "                          strides = strides)\n",
    "    x = layer_norm(x)\n",
    "    x = tf.nn.relu(x)\n",
    "    return x\n",
    "\n",
    "class Model:\n",
    "    def __init__(self):\n",
    "        self.X = tf.placeholder(tf.float32, (None, None))\n",
    "        feature = tf.expand_dims(self.X, axis = 2)\n",
    "        \n",
    "        for no, f in enumerate(features):\n",
    "            size_layers = f[0]\n",
    "            kernel_size = f[1]\n",
    "            strides = f[2]\n",
    "            with tf.variable_scope('feature_%d'%no):\n",
    "                feature = cnn_block(feature, size_layers, kernel_size, strides)\n",
    "        \n",
    "        if log_compression:\n",
    "            feature = tf.math.abs(feature)\n",
    "            feature = feature + 1\n",
    "            feature = tf.math.log(feature)\n",
    "        \n",
    "        x = tf.identity(feature)\n",
    "        for no, f in enumerate(aggs):\n",
    "            size_layers = f[0]\n",
    "            kernel_size = f[1]\n",
    "            strides = f[2]\n",
    "            with tf.variable_scope('agg_%d'%no):\n",
    "                x = cnn_aggregator(x, size_layers, kernel_size, strides)\n",
    "        \n",
    "        self.logits = x # X\n",
    "        self.targets = feature # Y\n",
    "        \n",
    "class RNN:\n",
    "    def __init__(\n",
    "        self,\n",
    "        num_layers,\n",
    "        size_layers,\n",
    "        learning_rate,\n",
    "        dropout = 1.0):\n",
    "        \n",
    "        self.label = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y_seq_len = tf.placeholder(tf.int32, [None])\n",
    "        self.Y = tf.sparse_placeholder(tf.int32)\n",
    "        self.model = Model()\n",
    "        \n",
    "        def cells(size, reuse = False):\n",
    "            return tf.contrib.rnn.DropoutWrapper(\n",
    "                tf.nn.rnn_cell.LSTMCell(\n",
    "                    size,\n",
    "                    initializer = tf.orthogonal_initializer(),\n",
    "                    reuse = reuse,\n",
    "                ),\n",
    "                state_keep_prob = dropout,\n",
    "                output_keep_prob = dropout,\n",
    "            )\n",
    "\n",
    "        features = self.model.targets\n",
    "        # features = self.model.logits\n",
    "        seq_lens = tf.fill([tf.shape(features)[0]], tf.shape(features)[1])\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (\n",
    "                state_fw,\n",
    "                state_bw,\n",
    "            ) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layers),\n",
    "                cell_bw = cells(size_layers),\n",
    "                inputs = features,\n",
    "                sequence_length = seq_lens,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d' % (n),\n",
    "            )\n",
    "            features = tf.concat((out_fw, out_bw), 2)\n",
    "            \n",
    "        logits = tf.layers.dense(features, len(vocab))\n",
    "        time_major = tf.transpose(logits, [1, 0, 2])\n",
    "        decoded, log_prob = tf.nn.ctc_greedy_decoder(time_major, seq_lens)\n",
    "        decoded = tf.to_int32(decoded[0])\n",
    "        self.preds = tf.sparse.to_dense(decoded)\n",
    "        self.cost = tf.reduce_mean(\n",
    "            tf.nn.ctc_loss(\n",
    "                self.Y,\n",
    "                time_major,\n",
    "                seq_lens\n",
    "            )\n",
    "        )\n",
    "        self.optimizer = tf.train.AdamOptimizer(\n",
    "            learning_rate = learning_rate\n",
    "        ).minimize(self.cost)\n",
    "        \n",
    "        preds = self.preds[:, :tf.reduce_max(self.Y_seq_len)]\n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        preds = pad_second_dim(preds, tf.reduce_max(self.Y_seq_len))\n",
    "        y_t = tf.cast(preds, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.label, masks)\n",
    "        self.mask_label = mask_label\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From <ipython-input-11-f8a53d00d0c4>:16: conv1d (from tensorflow.python.layers.convolutional) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.keras.layers.Conv1D` instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/init_ops.py:1251: calling VarianceScaling.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7a7c1fe358>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7a7c1fe358>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7a7c1fe358>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7a7c1fe358>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79b2c62d30>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79b2c62d30>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79b2c62d30>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79b2c62d30>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79fcfa0a20>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79fcfa0a20>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79fcfa0a20>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79fcfa0a20>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7a8d272080>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7a8d272080>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7a8d272080>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7a8d272080>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec64f438>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec64f438>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec64f438>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec64f438>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>>: AssertionError: Bad argument number for Name: 3, expecting 4\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79b2c62470>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79b2c62470>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79b2c62470>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f79b2c62470>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78981ff3c8>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78981ff3c8>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78981ff3c8>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78981ff3c8>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7898167198>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7898167198>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7898167198>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7898167198>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec6a5a20>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7898120cf8>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7898120cf8>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7898120cf8>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f7898120cf8>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec1264e0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec1264e0>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec1264e0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec1264e0>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec0d9cc0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec0d9cc0>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec0d9cc0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec0d9cc0>>: AssertionError: Bad argument number for Name: 3, expecting 4\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78980eb7f0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78980eb7f0>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78980eb7f0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78980eb7f0>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec0d9cc0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec0d9cc0>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec0d9cc0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f78ec0d9cc0>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f787806c358>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f787806c358>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f787806c358>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f787806c358>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f789820d358>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f789820d358>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f789820d358>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Conv1D.call of <tensorflow.python.layers.convolutional.Conv1D object at 0x7f789820d358>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:From <ipython-input-11-f8a53d00d0c4>:79: LSTMCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.LSTMCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-11-f8a53d00d0c4>:99: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn_cell_impl.py:961: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:Entity <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f787806c358>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f787806c358>>: AttributeError: module 'gast' has no attribute 'Num'\n",
      "WARNING: Entity <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f787806c358>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f787806c358>>: AttributeError: module 'gast' has no attribute 'Num'\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/ops/rnn.py:244: add_dispatch_support.<locals>.wrapper (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:Entity <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f78381bcfd0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f78381bcfd0>>: AttributeError: module 'gast' has no attribute 'Num'\n",
      "WARNING: Entity <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f78381bcfd0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f78381bcfd0>>: AttributeError: module 'gast' has no attribute 'Num'\n",
      "WARNING:tensorflow:Entity <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f789807d048>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f789807d048>>: AttributeError: module 'gast' has no attribute 'Num'\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING: Entity <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f789807d048>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f789807d048>>: AttributeError: module 'gast' has no attribute 'Num'\n",
      "WARNING:tensorflow:Entity <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f7a4f92ca58>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f7a4f92ca58>>: AttributeError: module 'gast' has no attribute 'Num'\n",
      "WARNING: Entity <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f7a4f92ca58>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method LSTMCell.call of <tensorflow.python.ops.rnn_cell_impl.LSTMCell object at 0x7f7a4f92ca58>>: AttributeError: module 'gast' has no attribute 'Num'\n",
      "WARNING:tensorflow:From <ipython-input-11-f8a53d00d0c4>:103: dense (from tensorflow.python.layers.core) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use keras.layers.dense instead.\n",
      "WARNING:tensorflow:Entity <bound method Dense.call of <tensorflow.python.layers.core.Dense object at 0x7f78381bcfd0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Dense.call of <tensorflow.python.layers.core.Dense object at 0x7f78381bcfd0>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING: Entity <bound method Dense.call of <tensorflow.python.layers.core.Dense object at 0x7f78381bcfd0>> could not be transformed and will be executed as-is. Please report this to the AutgoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause: converting <bound method Dense.call of <tensorflow.python.layers.core.Dense object at 0x7f78381bcfd0>>: AssertionError: Bad argument number for Name: 3, expecting 4\n",
      "WARNING:tensorflow:From <ipython-input-11-f8a53d00d0c4>:106: to_int32 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "\n",
    "size_layers = 512\n",
    "learning_rate = 1e-5\n",
    "num_layers = 2\n",
    "batch_size = 64\n",
    "epoch = 20\n",
    "\n",
    "model = RNN(num_layers, size_layers, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "import collections\n",
    "\n",
    "def get_assignment_map_from_checkpoint(tvars, init_checkpoint):\n",
    "    \"\"\"Compute the union of the current variables and checkpoint variables.\"\"\"\n",
    "    assignment_map = {}\n",
    "    initialized_variable_names = {}\n",
    "\n",
    "    name_to_variable = collections.OrderedDict()\n",
    "    for var in tvars:\n",
    "        name = var.name\n",
    "        m = re.match('^(.*):\\\\d+$', name)\n",
    "        if m is not None:\n",
    "            name = m.group(1)\n",
    "        name_to_variable[name] = var\n",
    "\n",
    "    init_vars = tf.train.list_variables(init_checkpoint)\n",
    "\n",
    "    assignment_map = collections.OrderedDict()\n",
    "    for x in init_vars:\n",
    "        (name, var) = (x[0], x[1])\n",
    "        if name not in name_to_variable:\n",
    "            continue\n",
    "        assignment_map[name] = name_to_variable[name]\n",
    "        initialized_variable_names[name] = 1\n",
    "        initialized_variable_names[name + ':0'] = 1\n",
    "\n",
    "    return (assignment_map, initialized_variable_names)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "tvars = tf.trainable_variables()\n",
    "\n",
    "checkpoint = 'wav2vec/model.ckpt'\n",
    "assignment_map, initialized_variable_names = get_assignment_map_from_checkpoint(tvars, \n",
    "                                                                                checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow/python/training/saver.py:1276: checkpoint_exists (from tensorflow.python.training.checkpoint_management) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use standard file APIs to check for files with this prefix.\n",
      "INFO:tensorflow:Restoring parameters from wav2vec/model.ckpt\n"
     ]
    }
   ],
   "source": [
    "saver = tf.train.Saver(var_list = assignment_map)\n",
    "saver.restore(sess, checkpoint)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [],
   "source": [
    "def pad_sentence_batch(sentence_batch, pad_int):\n",
    "    padded_seqs = []\n",
    "    seq_lens = []\n",
    "    max_sentence_len = max([len(sentence) for sentence in sentence_batch])\n",
    "    for sentence in sentence_batch:\n",
    "        padded_seqs.append(sentence + [pad_int] * (max_sentence_len - len(sentence)))\n",
    "        seq_lens.append(len(sentence))\n",
    "    return padded_seqs, seq_lens\n",
    "\n",
    "def sparse_tuple_from(sequences, dtype=np.int32):\n",
    "    indices = []\n",
    "    values = []\n",
    "\n",
    "    for n, seq in enumerate(sequences):\n",
    "        indices.extend(zip([n] * len(seq), range(len(seq))))\n",
    "        values.extend(seq)\n",
    "\n",
    "    indices = np.asarray(indices, dtype=np.int64)\n",
    "    values = np.asarray(values, dtype=dtype)\n",
    "    shape = np.asarray([len(sequences), np.asarray(indices).max(0)[1] + 1], dtype=np.int64)\n",
    "\n",
    "    return indices, values, shape"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [29:21<00:00,  6.88s/it, accuracy=0, cost=52.2]  \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:16<00:00,  1.78s/it, accuracy=0, cost=51.5]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg cost 114.518684, training avg accuracy 0.000226\n",
      "epoch 1, testing avg cost 50.557060, testing avg accuracy 0.000000\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.0472, cost=36.5]  \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:04<00:00,  2.25it/s, accuracy=0.058, cost=35.5] \n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg cost 41.367111, training avg accuracy 0.020455\n",
      "epoch 2, testing avg cost 34.974667, testing avg accuracy 0.059246\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.503, cost=27.5]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.30it/s, accuracy=0.499, cost=27.7]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 3, training avg cost 30.732441, training avg accuracy 0.245204\n",
      "epoch 3, testing avg cost 27.166332, testing avg accuracy 0.519087\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:37<00:00,  1.79s/it, accuracy=0.692, cost=21.4]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.27it/s, accuracy=0.754, cost=21.9]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 4, training avg cost 23.985298, training avg accuracy 0.644590\n",
      "epoch 4, testing avg cost 21.416052, testing avg accuracy 0.755946\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=17.5]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.26it/s, accuracy=0.754, cost=18]  \n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg cost 19.220715, training avg accuracy 0.755654\n",
      "epoch 5, testing avg cost 17.664839, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=15.5]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.28it/s, accuracy=0.754, cost=15.9]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 6, training avg cost 16.427927, training avg accuracy 0.760206\n",
      "epoch 6, testing avg cost 15.666548, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=15.9]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:04<00:00,  2.24it/s, accuracy=0.754, cost=16.1]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 7, training avg cost 15.426320, training avg accuracy 0.758643\n",
      "epoch 7, testing avg cost 15.823310, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=14.4]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.25it/s, accuracy=0.754, cost=14.7]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 8, training avg cost 14.885293, training avg accuracy 0.760206\n",
      "epoch 8, testing avg cost 14.469151, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=13.8]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.26it/s, accuracy=0.754, cost=14.1]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 9, training avg cost 14.135652, training avg accuracy 0.760206\n",
      "epoch 9, testing avg cost 13.947457, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=13.6]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.29it/s, accuracy=0.754, cost=13.8]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg cost 13.719376, training avg accuracy 0.760206\n",
      "epoch 10, testing avg cost 13.622516, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=13.2]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:04<00:00,  2.25it/s, accuracy=0.754, cost=13.5]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 11, training avg cost 13.426922, training avg accuracy 0.760206\n",
      "epoch 11, testing avg cost 13.336865, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=13]  \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:04<00:00,  2.22it/s, accuracy=0.754, cost=13.3]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 12, training avg cost 13.194747, training avg accuracy 0.760206\n",
      "epoch 12, testing avg cost 13.130510, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=12.8]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.25it/s, accuracy=0.754, cost=13.1]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg cost 13.005674, training avg accuracy 0.760206\n",
      "epoch 13, testing avg cost 12.951674, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=12.8]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:04<00:00,  2.24it/s, accuracy=0.754, cost=13]  \n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 14, training avg cost 12.843534, training avg accuracy 0.760206\n",
      "epoch 14, testing avg cost 12.846051, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.758, cost=12.4]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.26it/s, accuracy=0.754, cost=12.8]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg cost 12.705894, training avg accuracy 0.765272\n",
      "epoch 15, testing avg cost 12.647930, testing avg accuracy 0.759634\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.775, cost=12.3]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.26it/s, accuracy=0.762, cost=12.7]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg cost 12.564493, training avg accuracy 0.773266\n",
      "epoch 16, testing avg cost 12.510555, testing avg accuracy 0.771236\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:37<00:00,  1.79s/it, accuracy=0.775, cost=12.1]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:04<00:00,  2.19it/s, accuracy=0.762, cost=12.5]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg cost 12.436592, training avg accuracy 0.777291\n",
      "epoch 17, testing avg cost 12.379172, testing avg accuracy 0.771236\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.778, cost=12]  \n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:04<00:00,  2.25it/s, accuracy=0.773, cost=12.4]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg cost 12.315536, training avg accuracy 0.779853\n",
      "epoch 18, testing avg cost 12.256962, testing avg accuracy 0.778830\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:37<00:00,  1.79s/it, accuracy=0.786, cost=11.9]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.28it/s, accuracy=0.773, cost=12.3]\n",
      "minibatch loop:   0%|          | 0/256 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg cost 12.203173, training avg accuracy 0.780255\n",
      "epoch 19, testing avg cost 12.144290, testing avg accuracy 0.778830\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 256/256 [07:36<00:00,  1.78s/it, accuracy=0.786, cost=11.8]\n",
      "testing minibatch loop: 100%|██████████| 9/9 [00:03<00:00,  2.25it/s, accuracy=0.773, cost=12.2]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg cost 12.098604, training avg accuracy 0.780329\n",
      "epoch 20, testing avg cost 12.038074, testing avg accuracy 0.778830\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "from tqdm import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_cost, train_accuracy, test_cost, test_accuracy = [], [], [], []\n",
    "    for i in pbar:\n",
    "        batch_x = train_X[i : min(i + batch_size, len(train_X))]\n",
    "        batch_x = tf.keras.preprocessing.sequence.pad_sequences(\n",
    "            batch_x, dtype = 'float32', padding = 'post'\n",
    "        )\n",
    "        y = train_Y[i : min(i + batch_size, len(train_X))]\n",
    "        batch_y = sparse_tuple_from(y)\n",
    "        batch_label, batch_len = pad_sentence_batch(y, 0)\n",
    "        _, cost, accuracy = sess.run(\n",
    "            [model.optimizer, model.cost, model.accuracy],\n",
    "            feed_dict = {model.model.X: batch_x, model.Y: batch_y, \n",
    "                         model.label: batch_label, model.Y_seq_len: batch_len},\n",
    "        )\n",
    "        train_cost.append(cost)\n",
    "        train_accuracy.append(accuracy)\n",
    "        pbar.set_postfix(cost = cost, accuracy = accuracy)\n",
    "    \n",
    "    pbar = tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'testing minibatch loop')\n",
    "    for i in pbar:\n",
    "        batch_x = test_X[i : min(i + batch_size, len(test_X))]\n",
    "        batch_x = tf.keras.preprocessing.sequence.pad_sequences(\n",
    "            batch_x, dtype = 'float32', padding = 'post'\n",
    "        )\n",
    "        y = test_Y[i : min(i + batch_size, len(test_X))]\n",
    "        batch_y = sparse_tuple_from(y)\n",
    "        batch_label, batch_len = pad_sentence_batch(y, 0)\n",
    "        cost, accuracy = sess.run(\n",
    "            [model.cost, model.accuracy],\n",
    "            feed_dict = {model.model.X: batch_x, model.Y: batch_y, \n",
    "                         model.label: batch_label, model.Y_seq_len: batch_len},\n",
    "        )\n",
    "        \n",
    "        test_cost.append(cost)\n",
    "        test_accuracy.append(accuracy)\n",
    "        \n",
    "        pbar.set_postfix(cost = cost, accuracy = accuracy)\n",
    "    print('epoch %d, training avg cost %f, training avg accuracy %f'%(e + 1, np.mean(train_cost), \n",
    "                                                                      np.mean(train_accuracy)))\n",
    "    \n",
    "    print('epoch %d, testing avg cost %f, testing avg accuracy %f'%(e + 1, np.mean(test_cost), \n",
    "                                                                    np.mean(test_accuracy)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "real: say the word pearl\n",
      "predicted: say the word hae\n"
     ]
    }
   ],
   "source": [
    "import random\n",
    "\n",
    "random_index = random.randint(0, len(test_X) - 1)\n",
    "batch_x = test_X[random_index : random_index + 1]\n",
    "print(\n",
    "    'real:',\n",
    "    ''.join(\n",
    "        [idx2char[no] for no in test_Y[random_index : random_index + 1][0]]\n",
    "    ),\n",
    ")\n",
    "batch_y = sparse_tuple_from(test_Y[random_index : random_index + 1])\n",
    "pred = sess.run(model.preds, feed_dict = {model.model.X: batch_x})[0]\n",
    "print('predicted:', ''.join([idx2char[no] for no in pred]))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
